<template>
  <div class="add-inventory-container">
    <div class="header">
      <h5>添加盘点任务(按物品)</h5>
      <el-button @click="goBack" type="text" class="back-btn">
        <i class="el-icon-arrow-left"></i> 返回
      </el-button>
    </div>

    <!-- 任务详情表单 -->
    <el-card class="form-card" shadow="never">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认盘点人" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择盘点人" style="width: 100%">
                <el-option 
                  v-for="user in userList" 
                  :key="user.id" 
                  :label="user.name" 
                  :value="user.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点仓库" prop="storeId">
              <el-select v-model="form.storeId" placeholder="请选择仓库" style="width: 100%" @change="handleStoreChange">
                <el-option 
                  v-for="store in storeList" 
                  :key="store.id" 
                  :label="store.name" 
                  :value="store.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点时间" prop="takeDate">
              <el-date-picker 
                v-model="form.takeDate" 
                type="date" 
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="盘点备注" prop="note">
              <el-input 
                v-model="form.note" 
                type="textarea" 
                :rows="3" 
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 盘点物品选择 -->
    <el-card class="items-card" shadow="never" style="margin-top: 20px;">
      <template #header>
        <span class="card-header">盘点物品</span>
      </template>
      
      <div class="action-buttons">
        <el-button type="primary" @click="showProductModal">选择产品</el-button>
        <el-button type="success" @click="showGoodsModal">选择商品</el-button>
      </div>

      <!-- 已选物品表格 -->
      <el-table :data="selectedItems" border style="width: 100%; margin-top: 16px;">
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column prop="itemType" label="物品类型" width="100" />
        <el-table-column prop="tempZone" label="存放温区" width="100" />
        <el-table-column prop="category" label="物品品类" width="100" />
        <el-table-column prop="code" label="物品编码" width="120" />
        <el-table-column prop="name" label="物品名称" width="200" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-placeholder">分页控件</div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-section">
      <el-button type="primary" @click="previewItems">预览盘点物品</el-button>
      <el-button type="success" @click="generateTask">生成盘点任务</el-button>
    </div>

    <!-- 选择产品弹窗 -->
    <el-dialog v-model="productModalVisible" title="选择产品" width="80%" :before-close="closeProductModal">
      <div class="modal-content">
        <div class="search-section">
          <el-input v-model="productSearch.code" placeholder="产品编码" style="width: 200px; margin-right: 10px;" />
          <el-input v-model="productSearch.name" placeholder="产品名称" style="width: 200px; margin-right: 10px;" />
          <el-button type="primary" @click="searchProducts">查询</el-button>
        </div>
        
        <el-table :data="productList" border style="width: 100%; margin-top: 16px;">
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column prop="categoryName" label="所属品类" width="100" />
          <el-table-column prop="code" label="产品编码" width="120" />
          <el-table-column prop="name" label="产品名称" width="200" />
          <el-table-column prop="spec" label="产品规格" width="150" />
          <el-table-column prop="unit" label="计量单位" width="100" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="primary" size="small" @click="selectProduct(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-placeholder">分页控件</div>
      </div>
    </el-dialog>

    <!-- 选择商品弹窗 -->
    <el-dialog v-model="goodsModalVisible" title="选择商品" width="80%" :before-close="closeGoodsModal">
      <div class="modal-content">
        <div class="search-section">
          <el-input v-model="goodsSearch.code" placeholder="商品编码" style="width: 200px; margin-right: 10px;" />
          <el-input v-model="goodsSearch.name" placeholder="商品名称" style="width: 200px; margin-right: 10px;" />
          <el-button type="primary" @click="searchGoods">查询</el-button>
        </div>
        
        <el-table :data="goodsList" border style="width: 100%; margin-top: 16px;">
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column prop="categoryName" label="商品品类" width="100" />
          <el-table-column prop="code" label="商品编码" width="120" />
          <el-table-column prop="name" label="商品名称" width="200" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="primary" size="small" @click="selectGoods(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { queryAllStores, queryUserByStoreId, queryProductsByStoreId, queryCommodityByStoreId, AddStkByGoods } from '@/api/Inventory/addTask2.js'
import dayjs from 'dayjs'

const router = useRouter()

// 表单引用
const formRef = ref()

// 表单数据
const form = reactive({
  taskName: '',
  userId: '',
  storeId: 1,
  takeDate: dayjs().format('YYYY-MM-DD'),
  note: ''
})

// 表单验证规则
const rules = {
  taskName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请选择盘点人', trigger: 'change' }
  ],
  storeId: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  takeDate: [
    { required: true, message: '请选择盘点时间', trigger: 'change' }
  ]
}

// 用户列表
const userList = ref([])

// 仓库列表
const storeList = ref([])

// 已选物品列表
const selectedItems = ref([])

// 产品弹窗相关
const productModalVisible = ref(false)
const productSearch = reactive({
  code: '',
  name: ''
})
const productList = ref([])

// 商品弹窗相关
const goodsModalVisible = ref(false)
const goodsSearch = reactive({
  code: '',
  name: ''
})
const goodsList = ref([])

// 获取所有仓库
async function getStores() {
  try {
    const res = await queryAllStores()
    if (res && res.code === 200) {
      storeList.value = res.data
        .filter(store => store && store.id && store.name)
        .map(store => ({
          id: store.id,
          name: store.name
        }))
    } else {
      ElMessage.error('获取仓库列表失败')
    }
  } catch (error) {
    ElMessage.error('获取仓库列表失败')
  }
}

// 根据仓库ID获取用户
async function getUsersByStoreId(storeId) {
  try {
    const res = await queryUserByStoreId(storeId)
    if (res && res.code === 200) {
      // 后端返回单个TaskUser对象，需要转换为数组格式
      const userData = res.data
      if (userData && userData.userId && userData.name) {
        userList.value = [{
          id: userData.userId,
          name: userData.name
        }]
      } else {
        userList.value = []
      }
    } else {
      ElMessage.error('获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 根据仓库ID获取产品
async function getProductsByStoreId(params) {
  try {
    const res = await queryProductsByStoreId({
      storeId: params.storeId,
      page: 1,
      pageSize: 10
    })
    if (res && res.code === 200) {
      productList.value = res.data?.list || []
    } else {
      ElMessage.error('获取产品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取产品列表失败')
  }
}

// 根据仓库ID获取商品
async function getCommodityByStoreId(params) {
  try {
    const res = await queryCommodityByStoreId({
      storeId: params.storeId,
      page: 1,
      pageSize: 10
    })
    if (res && res.code === 200) {
      goodsList.value = res.data?.list || []
    } else {
      ElMessage.error('获取商品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  }
}

// 返回上一页
function goBack() {
  router.back()
}

// 显示产品选择弹窗
function showProductModal() {
  if (!form.storeId) {
    ElMessage.warning('请先选择盘点仓库')
    return
  }
  getProductsByStoreId({ storeId: form.storeId })
  productModalVisible.value = true
}

// 关闭产品选择弹窗
function closeProductModal() {
  productModalVisible.value = false
  productSearch.code = ''
  productSearch.name = ''
}

// 显示商品选择弹窗
function showGoodsModal() {
  if (!form.storeId) {
    ElMessage.warning('请先选择盘点仓库')
    return
  }
  getCommodityByStoreId({ storeId: form.storeId })
  goodsModalVisible.value = true
}

// 关闭商品选择弹窗
function closeGoodsModal() {
  goodsModalVisible.value = false
  goodsSearch.code = ''
  goodsSearch.name = ''
}

// 仓库选择变化处理
function handleStoreChange(storeId) {
  if (!storeId) return

  getUsersByStoreId(storeId)
  selectedItems.value = []
}

// 搜索产品
function searchProducts() {
  if (!form.storeId) {
    ElMessage.warning('请先选择盘点仓库')
    return
  }
  const params = { 
    storeId: form.storeId,
    code: productSearch.code,
    name: productSearch.name
  }
  getProductsByStoreId(params)
}

// 搜索商品
function searchGoods() {
  if (!form.storeId) {
    ElMessage.warning('请先选择盘点仓库')
    return
  }
  const params = { 
    storeId: form.storeId,
    code: goodsSearch.code,
    name: goodsSearch.name
  }
  getCommodityByStoreId(params)
}

// 选择产品
function selectProduct(product) {
  const newItem = {
    itemType: '产品',
    tempZone: '常温',
    category: product.categoryName,
    code: product.code,
    name: product.name,
    spec: product.spec,
    unit: product.unit
  }
  
  // 检查是否已存在相同编码的物品
  const exists = selectedItems.value.some(item => item.code === product.code)
  if (exists) {
    ElMessage.warning('该物品已存在，不能重复添加')
    return
  }
  
  selectedItems.value.push(newItem)
  closeProductModal()
  ElMessage.success('产品添加成功')
}

// 选择商品
function selectGoods(goods) {
  const newItem = {
    itemType: '商品',
    tempZone: '冷藏',
    category: goods.categoryName,
    code: goods.code,
    name: goods.name
  }
  
  // 检查是否已存在相同编码的物品
  const exists = selectedItems.value.some(item => item.code === goods.code)
  if (exists) {
    ElMessage.warning('该物品已存在，不能重复添加')
    return
  }
  
  selectedItems.value.push(newItem)
  closeGoodsModal()
  ElMessage.success('商品添加成功')
}

// 删除物品
function removeItem(index) {
  selectedItems.value.splice(index, 1)
  ElMessage.success('物品删除成功')
}

// 重置表单
function resetForm() {
  form.taskName = ''
  form.userId = ''
  form.storeId = 1
  form.takeDate = dayjs().format('YYYY-MM-DD')
  form.note = ''
  selectedItems.value = []
  userList.value = []
}

// 预览盘点物品
function previewItems() {
  ElMessage.info('预览功能待实现')
}

// 生成盘点任务
async function generateTask() {
  // 表单验证
  formRef.value?.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请完善表单信息')
      return
    }
    
    if (selectedItems.value.length === 0) {
      ElMessage.warning('请先选择盘点物品')
      return
    }
    
    try {
      // 构建提交数据
      const submitData = {
        codeList: selectedItems.value.map(item => item.code), // 物品编码集合
        note: form.note || '',
        stockId: form.storeId,
        takeDate: form.takeDate,
        taskName: form.taskName,
        taskType: 1, // 1-按物品
        userId: form.userId
      }
      
      console.log('提交的数据结构:', JSON.stringify(submitData, null, 2))
      
      // 调用API创建盘点任务
      const response = await AddStkByGoods(submitData)
      
      if (response && response.code === 200) {
        ElMessage.success('盘点任务生成成功')
        
        // 重置表单和选择项
        resetForm()
        
        // 跳转到盘点任务列表页面
        router.push('/Inventory/index.vue')
      } else {
        ElMessage.error('生成盘点任务失败：' + (response?.msg || '未知错误'))
      }
      
    } catch (error) {
      ElMessage.error('生成盘点任务失败：' + (error.message || '网络错误'))
    }
  })
}

onMounted(() => {
  getStores()
  handleStoreChange(1)
})
</script>

<style scoped>
.add-inventory-container {
  padding: 20px;
  background-color: white;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  font-size: 14px;
  color: #409eff;
}

.form-card {
  margin-bottom: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.items-card {
  margin-top: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.action-buttons {
  margin-bottom: 16px;
}

.action-section {
  margin-top: 20px;
  text-align: center;
}

.rules-section {
  margin-top: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-note {
  color: #606266;
  margin-bottom: 10px;
}

.task-rules {
  color: #606266;
}

.task-rules ol {
  margin-left: 20px;
}

.task-rules li {
  margin-bottom: 8px;
}

.modal-content {
  padding: 16px;
}

.search-section {
  margin-bottom: 16px;
}

.pagination-placeholder {
  text-align: center;
  padding: 10px;
  color: #909399;
  font-size: 14px;
  border-top: 1px solid #ebeef5;
  margin-top: 16px;
}
</style>